package com.baor.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baor.dao.RemovalWorkOrderDao;
import com.baor.domain.EquipmentVO;
import com.baor.domain.RemovalRecordVO;
import com.baor.domain.UserVO;
import com.baor.service.RemovalWorkOrderService;
import com.baor.util.R;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

@Service
public class RemovalWorkOrderServiceImpl implements RemovalWorkOrderService {

    @Autowired
    private RemovalWorkOrderDao removalWorkOrderDao;

    // 定义日期时间格式器
    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    public R getRemovalWorkOrderList(Map<String, Object> params) {
        try {
            // 获取分页参数
            int pageIndex = params.get("pageIndex") != null ? Integer.parseInt(params.get("pageIndex").toString()) : 1;
            int pageSize = params.get("pageSize") != null ? Integer.parseInt(params.get("pageSize").toString()) : 10;
            // 构建分页对象 - 注意这里修改了泛型类型为Map<String, Object>
            Page<Map<String, Object>> page = new Page<>(pageIndex, pageSize);
            // 构建联表查询条件
            MPJLambdaWrapper<RemovalRecordVO> wrapper = new MPJLambdaWrapper<>();
            wrapper.selectAll(RemovalRecordVO.class)
                    .select(UserVO::getUsername, UserVO::getPhone)
                    .select(EquipmentVO::getCode, EquipmentVO::getAddress)
                    .leftJoin(UserVO.class, UserVO::getId, RemovalRecordVO::getWorkerId)
                    .leftJoin(EquipmentVO.class, EquipmentVO::getId, RemovalRecordVO::getEquipmentId);
            // 筛选条件
            if (params.get("workOrderNo") != null && !params.get("workOrderNo").toString().isEmpty()) {
                wrapper.like(RemovalRecordVO::getClearanceWorkOrder, params.get("workOrderNo"));
            }
            if (params.get("workerId") != null) {
                wrapper.like(RemovalRecordVO::getWorkerId, params.get("workerId"));
            }
            if (params.get("startTime") != null && !params.get("startTime").toString().isEmpty()) {
                wrapper.ge(RemovalRecordVO::getRemovalTime, params.get("startTime"));
            }
            if (params.get("endTime") != null && !params.get("endTime").toString().isEmpty()) {
                wrapper.le(RemovalRecordVO::getRemovalTime, params.get("endTime"));
            }
            // 按清运时间倒序
            wrapper.orderByDesc(RemovalRecordVO::getRemovalTime);
            // 执行分页查询 - 这里的返回类型与page对象的泛型保持一致
            IPage<Map<String, Object>> resultPage = removalWorkOrderDao.selectJoinMapsPage(page, wrapper);
            // 封装结果
            Map<String, Object> result = new HashMap<>();
            result.put("list", resultPage.getRecords());
            result.put("totalSize", resultPage.getTotal());
//            result.put("pages", resultPage.getPages());
            result.put("pageIndex", pageIndex);
            result.put("pageSize", pageSize);
            return R.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            return R.er("查询清运工单失败: " + e.getMessage());
        }
    }

    @Override
    public R updateRemovalWorkOrder(Map<String, Object> params) {
        try {
            // 1. 获取参数
            Long id = Long.parseLong(params.get("id").toString());
            String workOrderNo = params.get("workOrderNo") != null ? params.get("workOrderNo").toString() : null;
            Long workerId = params.get("workerId") != null ? Long.parseLong(params.get("workerId").toString()) : null;
            Double weight = params.get("weight") != null ? Double.parseDouble(params.get("weight").toString()) : null;
            String removalTime = params.get("removalTime") != null ? params.get("removalTime").toString() : null;
            Long equipmentId = params.get("equipmentId") != null ? Long.parseLong(params.get("equipmentId").toString()) : null;
            Integer result = params.get("result") != null ? Integer.parseInt(params.get("result").toString()) : null;

            // 2. 查询记录是否存在
            RemovalRecordVO record = removalWorkOrderDao.selectById(id);
            if (record == null) {
                return R.er("清运工单不存在");
            }

            // 3. 更新字段（根据需求判断是否允许修改）
            if (workOrderNo != null) {
                record.setClearanceWorkOrder(workOrderNo); // 工单号
            }
            if (workerId != null) {
                record.setWorkerId(workerId); // 清运人员ID（关联用户表）
            }
            if (equipmentId != null) {
                record.setEquipmentId(equipmentId); // 设备ID（关联设备表）
            }
            if (removalTime != null) {
                // 如果removalTime字段在数据库中是String类型，直接设置字符串
                record.setRemovalTime(removalTime); // 清运时间
            }
            if (weight != null) {
                record.setWeight(weight); // 清运重量
            }
            if (result != null) {
                record.setResult(result); // 清运重量
            }

            // 4. 执行更新
            int updateCount = removalWorkOrderDao.updateById(record);
            if (updateCount > 0) {
                return R.ok("清运工单更新成功");
            } else {
                return R.er("清运工单更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.er("编辑清运工单失败: " + e.getMessage());
        }
    }
}